package singleton;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/22 22:29
 */
public class CASSingletonSafeTest {

    public static void main(String[] args) {
        new Thread(()->{
            System.out.println(CASSingletonSafe.getInstance());
        }).start();

        new Thread(()->{
            System.out.println(CASSingletonSafe.getInstance());
        }).start();
    }
}


//使用CAS实现单例模式--->线程安全
class CASSingletonSafe{

    //使用原子引用包裹该实例对象
    private static  final AtomicReference<CASSingletonSafe> INSTANCE
            = new AtomicReference<CASSingletonSafe>();

    //私有化构造器
    private CASSingletonSafe(){
    }

    public static CASSingletonSafe getInstance(){

        for(;;){//自旋
            CASSingletonSafe instance = INSTANCE.get();
            if(instance != null){//有instance，返回即可
                return instance;
            }
            //没有instance，进行cas，比较并交换
            INSTANCE.compareAndSet(null,new CASSingletonSafe());
            return INSTANCE.get();
        }
    }
}
